<script setup>
import {useRoute, useRouter} from "vue-router";
import {get, post} from "@/net/index.js";
import {computed, onMounted, reactive, ref} from "vue";
import {
  ArrowLeft,
  Avatar,
  ChatDotRound,
  CircleCheck,
  Delete,
  EditPen,
  Female,
  Male,
  Plus,
  Star
} from "@element-plus/icons-vue";
import axios from "axios";

const route = useRoute()
const topic = reactive({
  data:null,
  like:false,
  collect:false,
  comment:null,
  page:1,

})
const edit = ref(false)
const store = useStore()
const comment = reactive({
  show:false,
  text:"",
  quote:null

})
import { QuillDeltaToHtmlConverter } from 'quill-delta-to-html';
import router from "@/router/main.js";
import TopicTag from "@/components/views/forum/TopicTag.vue";
import Card from "@/componments/Card.vue";
import InteractButton from "@/componments/InteractButton.vue";
import {ElMessage} from "element-plus";
import {useStore} from "vuex";
import TopicEditor from "@/componments/TopicEditor.vue";
import TopicCommentEditor from "@/componments/TopicCommentEditor.vue";

const tid = route.params.tid
function updateTopic(editor){
  post(`/api/forum/update-topic`, {
    id: tid,
    type: editor.type, title : editor.title, content: editor.text
  }, data => {
    ElMessage.success("修改帖子成功")
    edit.value = false

  });

  init()
}
function initComment(page){
  topic.comment = null;
  topic.page = page;
  get(`api/forum/get-comment?tid=${tid}&page=${page-1}`, data => {
    topic.comment = data;
    console.log(data)
  });

}
function interact(type, message) {
  get(`/api/forum/interact?tid=${tid}&type=${type}&status=${!topic[type]}`,  () => {
    topic[type] = !topic[type];
    if(topic[type])
      ElMessage.success(` ${message}成功！`);
    else
      ElMessage.success(`已取消${message}！`);
  });
}
function init(){
  get(`api/forum/topic?tid=${tid}`, data => {
    topic.data = data;
    topic.like = data.interact.like;
    topic.collect = data.interact.collect;
    initComment(1);
  });
}

onMounted(() => {
init()
});
function convertDelta(data)  {
  const ops = JSON.parse(data).ops;
  const converter = new QuillDeltaToHtmlConverter(ops, { inlineStyles: true });
  return converter.convert();
};
function deleteComment(id){
  get(`/api/forum/delete-comment?id=${id}`, () => {
    ElMessage.success("删除评论成功")
    initComment(Math.ceil(--topic.data.commentCount / 5))
  } );
}
function avatarGet(avatar){
  if(avatar)
    return `${axios.defaults.baseURL}/images/${avatar}`
  return "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
}
</script>

<template>
  <div class="topic-page" v-if="topic.data">
    <div class="topic-main" style="position: sticky;top: 0;z-index:10">
      <card style="display: flex;width: 100%;">
        <el-button type="primary" :icon="ArrowLeft" @click="router.push('/index')" plain round>
        返回列表
        </el-button>

        <div style="text-align: center;font-weight: bold;padding: 3px;flex: 1">
          <TopicTag style="margin-right: 10px" :type="topic.data.type"></TopicTag>
          <span>{{topic.data.title}}</span>
        </div>

      </card>
    </div>
    <div class="topic-main">
      <div class="topic-main-left">
        <el-avatar size="large" :src="avatarGet(topic.data.user.avatar)"></el-avatar>
      <div>
        <div style="font-size: 18px;font-weight: bold">
          {{topic.data.user.username}}
          <span style="color: hotpink" v-if="topic.data.user.gender === 1">
  <el-icon><Female></Female></el-icon>
</span>
          <span style="color: dodgerblue" v-if="topic.data.user.gender === 0">
  <el-icon><Male></Male></el-icon>
</span>
        </div>
        <div class="desc">{{topic.data.user.email}}</div>

      </div>
        <el-divider style="margin: 10px 0;text-align: left"></el-divider>
        <div>
          <div class="desc">微信号：{{topic.data.user.vx || '已隐藏或未填写'}}</div>
          <div class="desc">QQ号：{{topic.data.user.qq || '已隐藏或未填写'}}</div>
          <div class="desc">手机号：{{topic.data.user.phone || '已隐藏或未填写'}}</div>

        </div>
        <el-divider style="margin: 10px 0"></el-divider>
        <div class="desc">描述：{{topic.data.user.des}}</div>
      </div>
      <div class="topic-main-right">
        <div class="topic-content" v-html="convertDelta(topic.data.content)">
        </div>
        <el-divider></el-divider>
        <div>

            <span style="font-size: 13px;color: grey">发帖时间：{{new Date(topic.data.time).toLocaleString()}}</span>
        </div>
        <div style="text-align: right;margin-top: 30px">
          <interact-button name="编辑帖子" color="blue"   :check="false"
                           @click="edit=true" v-if="store.state.user.id === topic.data.user.id">
            <el-icon><EditPen></EditPen></el-icon>
          </interact-button>
          <interact-button name="点个赞吧" color="red"  check-name="已点赞" :check="topic.like"
          @check="interact('like', '点赞')">
            <el-icon><CircleCheck></CircleCheck></el-icon>
          </interact-button>
          <interact-button name="收藏本贴" color="green":check="topic.collect" check-name="已收藏"
          @check="interact('collect', '收藏')">
            <el-icon><Star></Star></el-icon>
          </interact-button>
        </div>

      </div>

    </div>
    <transition name="fade-scale" mode="in-out" >
      <div v-if="topic.comment">
        <div class="topic-main" style="margin-top: 10px" v-for="item in topic.comment">
          <div class="topic-main-left">
            <el-avatar size="large" :src="avatarGet(item.user.avatar)"></el-avatar>
            <div>
              <div style="font-size: 18px;font-weight: bold">
                {{item.user.username}}
                <span style="color: hotpink" v-if="item.user.gender === 1">
  <el-icon><Female></Female></el-icon>
</span>
                <span style="color: dodgerblue" v-if="item.user.gender === 0">
  <el-icon><Male></Male></el-icon>
</span>
              </div>
              <div class="desc">{{item.user.email}}</div>

            </div>
            <el-divider style="margin: 10px 0;text-align: left"></el-divider>
            <div>
              <div class="desc">微信号：{{item.user.vx || '已隐藏或未填写'}}</div>
              <div class="desc">QQ号：{{item.user.qq || '已隐藏或未填写'}}</div>
              <div class="desc">手机号：{{item.user.phone || '已隐藏或未填写'}}</div>

            </div>
            <el-divider style="margin: 10px 0"></el-divider>
          </div>
          <div class="topic-main-right">

            <span style="font-size: 13px;color: grey">评论时间：{{new Date(item.time).toLocaleString()}}</span>
            <div v-if="item.quote" class="quote-comment">
              回复：{{item.quote}}
            </div>
            <div class="topic-content" v-html="convertDelta(item.content)">
            </div>
            <div style="text-align: right;margin-top: 100px">
                <el-link style="margin-right: 20px" type="primary" :icon="ChatDotRound" @click="comment.quote=item;comment.show=true">
                  &nbsp;回复评论
                </el-link>
              <el-link type="danger" @click="deleteComment(item.id)" :icon="Delete" v-if="store.state.user.id === item.user.id" >
                &nbsp;删除评论
              </el-link>
            </div>
          </div>
        </div>
        <div style="margin: 10px auto;width: fit-content">
          <el-pagination v-model:current-page="topic.page" @current-change="initComment"
                         :page-size="5" :total="topic.data.commentCount"
          hide-on-single-page>

          </el-pagination>
        </div>
      </div>
    </transition>
<topic-editor :show="edit" @close="edit=false" v-if="topic.data"
:default-type="topic.data.type" :default-title="topic.data.title" :default-text="topic.data.content" submit-button="更新帖子内容" :submit-click="updateTopic"></topic-editor>
    <TopicCommentEditor :show="comment.show" @update="initComment(Math.ceil(++topic.data.commentCount / 5))"  @close="comment.show=false" :tid="tid" :quote="comment.quote" ></TopicCommentEditor>

    <div class="add-content" @click="comment.show=true;comment.quote=null" >
    <el-icon><Plus></Plus></el-icon>
  </div>
    </div>


</template>

<style scoped>
.quote-comment{
  font-size:13px;color:grey;background-color:rgba(94,94,94,0.1);padding:10px;margin-top:10px;border-radius:5px;
}
.add-content{
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  font-size: 18px;
  color: var( --el-color-primary);
  text-align: center;
  line-height: 45px;
  background: var( --el-bg-color-overlay);
  box-shadow: var( --el-box-shadow-lighter);
  &:hover {
  background: var( --el-border-color-extra-light);
  cursor: pointer;
}

}
.topic-page {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px 0;
}


.topic-main {
  display: flex;
  border-radius: 7px;
  margin: 0 auto;
  background-color: var(--el-bg-color);
  width: 800px;
}

.topic-main-left {
  width: 200px;
  padding: 10px;
  border-right: solid 1px var(--el-border-color);
}

.topic-main-right {
  width: 600px;
  padding: 10px 20px;
  .topic-content{
    max-width: 500px;
    font-size: 14px;
    line-height: 22px;
    opacity: 0.8;
  }
  .topic-content img {
    max-width: 100%;
    height: auto;
  }
}
.desc{
  font-size: 14px;
  color: #999;
}
.fade-scale-enter-active,
.fade-scale-leave-active {
  transition: all 0.5s ease-out;
}
.fade-scale-enter-from,
.fade-scale-leave-to {
  transform: scale(0.9);
  opacity: 0;
}
.fade-scale-enter-to,
.fade-scale-leave-from {
  transform: scale(1);
  opacity: 1;
}
</style>